package com.cet6.controller;

import com.cet6.common.Result;
import com.cet6.entity.StudyRecord;
import com.cet6.service.StudyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/study-records")
public class StudyRecordController {
    
    @Autowired
    private StudyRecordService studyRecordService;
    
    /**
     * 添加或更新学习记录
     * @param studyRecord 学习记录
     * @return 操作结果
     */
    @PostMapping
    public Result<String> saveOrUpdateStudyRecord(@RequestBody StudyRecord studyRecord) {
        try {
            // 参数验证
            if (studyRecord.getUserId() == null || studyRecord.getUserId() <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            if (studyRecord.getWordId() == null || studyRecord.getWordId() <= 0) {
                return Result.error(400, "单词ID不能为空或无效");
            }
            if (studyRecord.getStatus() == null || studyRecord.getStatus() < 0 || studyRecord.getStatus() > 2) {
                return Result.error(400, "学习状态无效，应为0-2之间的值");
            }
            if (studyRecord.getMasteryLevel() == null || studyRecord.getMasteryLevel() < 0 || studyRecord.getMasteryLevel() > 100) {
                return Result.error(400, "掌握程度无效，应为0-100之间的值");
            }
            
            boolean success = studyRecordService.saveOrUpdateStudyRecord(studyRecord);
            if (success) {
                return Result.success("学习记录保存成功");
            } else {
                return Result.error("学习记录保存失败");
            }
        } catch (Exception e) {
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID和单词ID获取学习记录
     * @param userId 用户ID
     * @param wordId 单词ID
     * @return 学习记录
     */
    @GetMapping
    public Result<StudyRecord> getStudyRecord(
            @RequestParam Long userId,
            @RequestParam Long wordId) {
        try {
            // 参数验证
            if (userId == null || userId <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            if (wordId == null || wordId <= 0) {
                return Result.error(400, "单词ID不能为空或无效");
            }
            
            StudyRecord studyRecord = studyRecordService.getStudyRecordByUserIdAndWordId(userId, wordId);
            if (studyRecord == null) {
                return Result.error(404, "学习记录不存在");
            }
            
            return Result.success("查询成功", studyRecord);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }
}
